<template>
  <el-dialog
    v-model="dialogVisible"
    :title="providerInfo && providerInfo.row ? providerInfo.row.provider + '配置' : '配置'"
    width="500"
  >
    <form-create v-model:api="fApi" v-loading="loading" :rule="rule" :option="options" />
    <template #footer>
      <div class="dialog-footer">
        <el-button :disabled="loading" @click="handleClose">取消</el-button>
        <el-button type="primary" :disabled="loading" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import ProviderAPI from "@/api/virtual-number/provider.api"
import useToggle from "@/hooks/useToggle"
const [loading, setLoading] = useToggle()
const [dialogVisible, setDialogVisible] = useToggle()

const emits = defineEmits(["saveData"])

const providerInfo = ref({})
const init = (e) => {
  console.log(e)

  setDialogVisible(true)

  nextTick(() => {
    if (e) {
      providerInfo.value = e
      getFormConfig(e)
    }
  })
}

const rule = ref([])
const getFormConfig = (e) => {
  setLoading(true)
  ProviderAPI.uischema(e.row.provider)
    .then((res) => {
      rule.value = Array.isArray(res)
        ? res.map((item) => {
            if (providerInfo.value.row.configuration) {
              item.value = providerInfo.value.row.configuration[item.field] || ""
            }
            return item
          })
        : []

      nextTick(() => {
        const submitButton = document.querySelector(".fc-form-item .fc-submit-btn")
        if (submitButton) submitButton.style.display = "none"
      })
    })
    .finally(() => setLoading(false))
}

const fApi = ref({})
const options = {
  onSubmit: (formData) => {
    console.log(formData)
    emits("saveData", {
      data: formData,
      ...providerInfo.value,
    })
    handleClose()
  },
}

const submit = async () => {
  const submitButton = document.querySelector(".fc-form-item .fc-submit-btn")
  if (submitButton) submitButton.click()
}

const handleClose = () => {
  setDialogVisible(false)
}

defineExpose({
  init,
})
</script>
